package com.cyf.app.service.impl;

import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.cyf.app.network.bean.*;
import com.cyf.app.service.AppPayService;
import com.cyf.pay.util.WxNoSensepayConfig;
import com.cyf.pay.wxpay.service.WxNoSensePayService;
import com.cyf.service.ApiUserService;
import com.cyf.service.CheckParam;
import com.cyf.db.bean.ad.AdPayOrder;
import com.cyf.db.mapper.ad.AdPayOrderMapper;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.pay.alipay.service.AlipayService;
import com.cyf.pay.wxpay.bean.*;
import com.cyf.pay.wxpay.service.WxpayService;
import com.cyf.service.AdPayOrderService;
import com.cyf.service.PayOrderService;
import com.cyf.service.bean.CustomException;
import com.cyf.util.*;
import com.cyf.wechat.network.bean.WechatBusinessRsp;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import static com.cyf.pay.wxpay.bean.WxpayUnifiedOrderRsp.FAIL;

/**
 * app相关接口
 * Created by cage on 2017/2/15.
 */
@Service
public class AppPayServiceImpl implements AppPayService {
    private static Logger logger = LoggerFactory.getLogger(AppPayServiceImpl.class);
    private static final SimpleDateFormat OUTTIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private WxpayService wxpayService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private CheckParam checkParam;
    @Autowired
    private AdPayOrderMapper adPayOrderMapper;
    @Autowired
    private AdPayOrderService adPayOrderService;
    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private FeeGroupMapper groupMapper;
    @Autowired
    private LocalAdminparaMapper localAdminparaMapper;
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private WxNoSensePayService wxNoSensePayService;

    @Override
    public AppWxpayUnifiedOrderRsp wxpayUnifiedOrder(AppWxpayUnifiedOrderReq req) {
        switch (req.getType()) {
            case AppWxpayUnifiedOrderReq.TYPE_PARKING_FEE:
                return wxpayUnifiedOrderForParkingFee(req);
            case AppWxpayUnifiedOrderReq.TYPE_AD_FEE:
                return wxpayUnifiedOrderForAdFee(req);
            default: {
                AppWxpayUnifiedOrderRsp rsp = new AppWxpayUnifiedOrderRsp();
                rsp.setResult(AppBusinessRsp.FAIL);
                rsp.setStrError("请求参数异常！");
                return rsp;
            }
        }
    }

    @Override
    public AppWxpayUnifiedOrderRsp wxpayMonthlyOrder(AppWxpayUnifiedOrderReq req) {
        AppWxpayUnifiedOrderRsp rsp = new AppWxpayUnifiedOrderRsp();
        rsp.setResult(ApiWxUnifiedOrderRsp.FAIL);
        logger.info("微信月租延期，订单号:{},请求微信公众号统一下单", req.getOrderNo());
        PayOrder payOrder = payOrderMapper.getByOrderNo(req.getOrderNo());
        if (payOrder == null) {
            rsp.setResult(ApiWxUnifiedOrderRsp.FAIL);
            rsp.setStrError("订单号错误!");
            return rsp;
        }

        LocalAdminpara adminpara = localAdminparaMapper.getByParkingIdAndParaKey(payOrder.getParkingId(), LocalAdminpara.SCANCODE_PAY);
        if (adminpara == null || !"1".equals(adminpara.getParaValue())) {
            rsp.setStrError("该车场未开通支付功能！");
            payOrderService.updatePayFailOrderStatus(payOrder.getId(), PayOrder.TRADETYPE_SCAN,
                    PayOrder.PAY_WAY_WECHAT, 1, 0);
            return rsp;
        }

        ApiUser apiUser = apiUserService.getLastApiUserNoCyfByParkingId(payOrder.getParkingId(), false);
        if (apiUser == null) {
            rsp.setStrError("该车场未开通支付功能！");
            payOrderService.updatePayFailOrderStatus(payOrder.getId(), PayOrder.TRADETYPE_SCAN,
                    PayOrder.PAY_WAY_WECHAT, 1, 0);
            return rsp;
        }

        WxChatUnifiedOrderReq wxChatUnifiedOrderReq = new WxChatUnifiedOrderReq();
        //支付金额
        int fee = payOrder.getFee();
        wxChatUnifiedOrderReq.setOut_trade_no(payOrder.getOrderNo());
        wxChatUnifiedOrderReq.setTotal_fee(fee < 0 ? 0 : fee);
        //子商户号 必传字段
        wxChatUnifiedOrderReq.setSub_mch_id(apiUser.getServiceSubMchId());
        String serviceOpenId = getServiceOpenId(req.getCode());
        if (StringUtils.isNotEmpty(apiUser.getServiceWxSubAppid())) {
            //子商户 app_id 允许为null
            wxChatUnifiedOrderReq.setSub_appid(apiUser.getServiceWxSubAppid());
            wxChatUnifiedOrderReq.setSub_openid(serviceOpenId);
        } else {
            wxChatUnifiedOrderReq.setOpenid(serviceOpenId);
        }
        wxChatUnifiedOrderReq.setAttach("parkingFee");
        wxChatUnifiedOrderReq.setAppid(apiUser.getWxIsvAppId());
        wxChatUnifiedOrderReq.setMch_id(apiUser.getWxIsvMchId());
        WxChatUnifiedOrderRsp wxChatUnifiedOrderRsp =
                wxNoSensePayService.unifiedOrder(wxChatUnifiedOrderReq, apiUser.getWxIsvKey());
        if ("SUCCESS".equals(wxChatUnifiedOrderRsp.getReturn_code()) &&
                "SUCCESS".equals(wxChatUnifiedOrderRsp.getResult_code())) {
            rsp.setAppId(wxChatUnifiedOrderRsp.getAppid());
            rsp.setNonceStr(WxpayCore.nonce_str(64));
            rsp.setTimeStamp(System.currentTimeMillis() / 1000 + "");
            rsp.setPackageStr("prepay_id=" + wxChatUnifiedOrderRsp.getPrepay_id());
            rsp.setSignType("MD5");
            try {
                rsp.setPaySign(WxpayCore.sign(SignUtil.bean2TreeMap(rsp), WxNoSensepayConfig.KEY));
            } catch (UnsupportedEncodingException e) {
                logger.error("【微信证书签名错误】错误原因：{}", e.getMessage());
                e.printStackTrace();
            }
            rsp.setResult(ApiWxUnifiedOrderRsp.SUCCESS);
            updatePayWayAtUndefiedOrder(payOrder.getId(), PayOrder.TRADETYPE_SCAN, PayOrder.PAY_WAY_WECHAT, 1,
                    apiUser.getId());
        } else {
            rsp.setResult(ApiWxUnifiedOrderRsp.FAIL);
            //通信标识错误
            logger.error("微信公众号统一下单接口异常:{} {} {} {} {} {}",
                    wxChatUnifiedOrderRsp.getReturn_code(),
                    wxChatUnifiedOrderRsp.getReturn_msg(),
                    wxChatUnifiedOrderRsp.getResult_code(),
                    wxChatUnifiedOrderRsp.getErr_code(),
                    wxChatUnifiedOrderRsp.getErr_code_des(),
                    apiUser.getName());
            rsp.setStrError("微信下单失败，请稍后重试！");
            payOrderService.updatePayFailOrderStatus(payOrder.getId(), PayOrder.TRADETYPE_SCAN,
                    PayOrder.PAY_WAY_WECHAT, 1, apiUser.getId());
        }

        return rsp;
    }

    @Override
    public WechatBusinessRsp monthlyOrderResult(String orderNo) {
        WechatBusinessRsp rsp = new WechatBusinessRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            PayOrder payOrder = payOrderMapper.getByOrderNo(orderNo);
            if (payOrder == null) {
                rsp.setStrError("订单号错误！");
            }
            if (payOrder.getPayStatus() == PayOrder.PAY_SUCCESS) {
                Parking parking = parkingMapper.getParkingById(payOrder.getParkingId());
                Map map = new HashMap();
                map.put("parkingName", parking.getName());
                map.put("payTime", DateUtil.formatDate(payOrder.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
                map.put("fee", payOrder.getFee());
                map.put("month", payOrder.getMonth());
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setData(map);
            } else {
                rsp.setStrError("稍后再试！");
            }

        } catch (Exception e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        return rsp;
    }

    /**
     * 支付停车费
     *
     * @param req AppWxpayUnifiedOrderReq
     * @return AppWxpayUnifiedOrderRsp
     */
    private AppWxpayUnifiedOrderRsp wxpayUnifiedOrderForParkingFee(AppWxpayUnifiedOrderReq req) {
        AppWxpayUnifiedOrderRsp rsp = new AppWxpayUnifiedOrderRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            PayOrder payOrder = payOrderMapper.getByOrderNo(req.getOrderNo());
            if (payOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (payOrder.getPayStatus() == PayOrder.PAY_SUCCESS) {
                rsp.setStrError("订单已经支付！");
                return rsp;
            }

            WxpayUnifiedOrderReq unifiedOrder = new WxpayUnifiedOrderReq(WxpayConfig.APP_ID, WxpayConfig.MCH_ID, WxpayConfig.NOTIFY_PAY, WxpayConfig.TRADE_TYPE_APP);
            unifiedOrder.setBody("支付停车费");
            unifiedOrder.setOut_trade_no(req.getOrderNo());
            unifiedOrder.setTotal_fee(payOrder.getFee());
            unifiedOrder.setSpbill_create_ip(req.getIp());
            unifiedOrder.setAttach("支付停车费");
            WxpayUnifiedOrderRsp wxpayUnifiedOrderRsp = wxpayService.unifiedOrder(unifiedOrder);
            if (FAIL.equals(wxpayUnifiedOrderRsp.getReturn_code()) || FAIL.equals(wxpayUnifiedOrderRsp.getResult_code())) {
                rsp.setStrError("统一下单失败！");
                return rsp;
            }
            logger.info("APP微信付款统一下单成功，开始生成带签名的客户端支付信息");
            PreparedPayReq preparedPayReq = wxpayService.getPreparedPayReq(wxpayUnifiedOrderRsp);
            BeanUtils.copyProperties(preparedPayReq, rsp);
            // 更新订单的支付方式
            payOrder.setPayWay(PayOrder.PAY_WAY_WECHAT);
            payOrderMapper.updatePayWay(payOrder.getId(), payOrder.getPayWay());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("APP微信付款统一下单异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    /**
     * 支付广告费
     *
     * @param req AppWxpayUnifiedOrderReq
     * @return AppWxpayUnifiedOrderRsp
     */
    private AppWxpayUnifiedOrderRsp wxpayUnifiedOrderForAdFee(AppWxpayUnifiedOrderReq req) {
        AppWxpayUnifiedOrderRsp rsp = new AppWxpayUnifiedOrderRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            AdPayOrder adPayOrder = adPayOrderMapper.getByOrderNo(req.getOrderNo());
            if (adPayOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (adPayOrder.getStatus() != AdPayOrder.STATUS_WAIT_PAY) {
                rsp.setStrError("订单已完成！");
                return rsp;
            }

            WxpayUnifiedOrderReq unifiedOrder = new WxpayUnifiedOrderReq(WxpayConfig.APP_ID, WxpayConfig.MCH_ID, WxpayConfig.NOTIFY_PAY, WxpayConfig.TRADE_TYPE_APP);
            unifiedOrder.setBody("支付广告费");
            unifiedOrder.setOut_trade_no(req.getOrderNo());
            unifiedOrder.setTotal_fee(adPayOrder.getTxnAmt());
            unifiedOrder.setSpbill_create_ip(req.getIp());
            unifiedOrder.setAttach("支付广告费");
            WxpayUnifiedOrderRsp wxpayUnifiedOrderRsp = wxpayService.unifiedOrder(unifiedOrder);
            if (FAIL.equals(wxpayUnifiedOrderRsp.getReturn_code()) || FAIL.equals(wxpayUnifiedOrderRsp.getResult_code())) {
                rsp.setStrError("统一下单失败！");
                return rsp;
            }
            logger.info("APP微信付款统一下单成功，开始生成带签名的客户端支付信息");
            PreparedPayReq preparedPayReq = wxpayService.getPreparedPayReq(wxpayUnifiedOrderRsp);
            BeanUtils.copyProperties(preparedPayReq, rsp);
            // 更新订单的支付方式
            adPayOrderMapper.updatePayWay(AdPayOrder.TRADETYPE_APP, AdPayOrder.PAYWAY_WECHAT, adPayOrder.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("APP微信付款统一下单异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppWxpayQueryOrderRsp wxpayQueryOrder(AppWxpayQueryOrderReq req) {
        AppWxpayQueryOrderRsp rsp = new AppWxpayQueryOrderRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        AppBusinessRsp appBusinessRsp;
        switch (req.getType()) {
            case AppWxpayQueryOrderReq.TYPE_PARKING_FEE:
                appBusinessRsp = queryOrderForParkingFee(req.getTransactionId(), req.getOrderNo(), PayOrder.PAY_WAY_WECHAT);
                break;
            case AppWxpayQueryOrderReq.TYPE_AD_FEE:
                appBusinessRsp = queryOrderForAdFee(req.getTransactionId(), req.getOrderNo(), AdPayOrder.PAYWAY_WECHAT);
                break;
            default: {
                rsp.setStrError("请求参数异常！");
                return rsp;
            }
        }
        rsp.setResult(appBusinessRsp.getResult());
        rsp.setStrError(appBusinessRsp.getStrError());
        return rsp;
    }

    @Override
    public AppAlipayUnifiedOrderRsp alipayUnifiedOrder(AppAlipayUnifiedOrderReq req) {
        switch (req.getType()) {
            case AppAlipayUnifiedOrderReq.TYPE_PARKING_FEE:
                return alipayUnifiedOrderForParkingFee(req);
            case AppAlipayUnifiedOrderReq.TYPE_AD_FEE:
                return alipayUnifiedOrderForAdFee(req);
            default: {
                AppAlipayUnifiedOrderRsp rsp = new AppAlipayUnifiedOrderRsp();
                rsp.setResult(AppBusinessRsp.FAIL);
                rsp.setStrError("请求参数异常！");
                return rsp;
            }
        }

    }

    /**
     * 支付停车费
     *
     * @param req
     * @return
     */
    private AppAlipayUnifiedOrderRsp alipayUnifiedOrderForParkingFee(AppAlipayUnifiedOrderReq req) {
        AppAlipayUnifiedOrderRsp rsp = new AppAlipayUnifiedOrderRsp();
        rsp.setResult(-1);
        try {
            checkParam.getAppUser(req.getToken());
            PayOrder payOrder = payOrderMapper.getByOrderNo(req.getOrderNo());
            if (payOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (payOrder.getPayStatus() == PayOrder.PAY_SUCCESS) {
                rsp.setStrError("订单已经支付！");
                return rsp;
            }
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("支付停车费");
            model.setSubject("支付停车费");
            model.setOutTradeNo(req.getOrderNo());
            model.setTotalAmount((payOrder.getFee() * 0.01) + ""); // 单位为元
            AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayService.unifiedOrder(model);
            if (alipayTradeAppPayResponse != null && alipayTradeAppPayResponse.isSuccess()) {
                //就是orderString 可以直接给客户端请求，无需再做处理。
                rsp.setOrderInfo(alipayTradeAppPayResponse.getBody());

                // 更新支付方式
                payOrder.setPayWay(PayOrder.PAY_WAY_ALIPAY);
                payOrderMapper.updatePayWay(payOrder.getId(), payOrder.getPayWay());
                rsp.setResult(AppBusinessRsp.SUCCESS);
            } else {
                rsp.setStrError("统一下单失败！");
                return rsp;
            }
        } catch (Exception e) {
            logger.error("APP支付宝付款下单异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    /**
     * 支付广告费
     *
     * @param req
     * @return
     */
    private AppAlipayUnifiedOrderRsp alipayUnifiedOrderForAdFee(AppAlipayUnifiedOrderReq req) {
        AppAlipayUnifiedOrderRsp rsp = new AppAlipayUnifiedOrderRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            AdPayOrder adPayOrder = adPayOrderMapper.getByOrderNo(req.getOrderNo());
            if (adPayOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (adPayOrder.getStatus() != AdPayOrder.STATUS_WAIT_PAY) {
                rsp.setStrError("订单已完成！");
                return rsp;
            }
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("支付广告费");
            model.setSubject("支付广告费");
            model.setOutTradeNo(req.getOrderNo());
            model.setTotalAmount((adPayOrder.getTxnAmt() * 0.01) + ""); // 单位为元
            AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayService.unifiedOrder(model);
            if (alipayTradeAppPayResponse != null && alipayTradeAppPayResponse.isSuccess()) {
                //就是orderString 可以直接给客户端请求，无需再做处理。
                rsp.setOrderInfo(alipayTradeAppPayResponse.getBody());
                // 更新支付方式
                adPayOrderMapper.updatePayWay(AdPayOrder.TRADETYPE_APP, AdPayOrder.PAYWAY_ALIPAY, adPayOrder.getId());
                rsp.setResult(AppBusinessRsp.SUCCESS);
            } else {
                rsp.setStrError("统一下单失败！");
                return rsp;
            }
        } catch (Exception e) {
            logger.error("APP支付宝付款下单异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppAlipayQueryOrderRsp alipayQueryOrder(AppAlipayQueryOrderReq req) {
        AppAlipayQueryOrderRsp rsp = new AppAlipayQueryOrderRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        AppBusinessRsp appBusinessRsp;
        switch (req.getType()) {
            case AppAlipayQueryOrderReq.TYPE_PARKING_FEE:
                appBusinessRsp = queryOrderForParkingFee(req.getTransactionId(), req.getOrderNo(), PayOrder.PAY_WAY_ALIPAY);
                break;
            case AppAlipayQueryOrderReq.TYPE_AD_FEE:
                appBusinessRsp = queryOrderForAdFee(req.getTransactionId(), req.getOrderNo(), AdPayOrder.PAYWAY_ALIPAY);
                break;
            default: {
                rsp.setStrError("请求参数异常！");
                return rsp;
            }
        }
        rsp.setResult(appBusinessRsp.getResult());
        rsp.setStrError(appBusinessRsp.getStrError());
        return rsp;
    }

    /**
     * 查询停车费订单
     *
     * @param transactionId 交易订单号
     * @param orderNo       商户订单号
     * @param payWay        支付方式
     * @return AppBusinessRsp
     */
    private AppBusinessRsp queryOrderForParkingFee(String transactionId, String orderNo, int payWay) {
        AppBusinessRsp rsp = new AppBusinessRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        try {
            PayOrder payOrder = null;
            // 优先根据transactionId查询
            if (!StringUtils.isEmpty(transactionId)) {
                payOrder = payOrderMapper.getByTransactionId(transactionId);
            } else if (!StringUtils.isEmpty(orderNo)) {
                payOrder = payOrderMapper.getByOrderNo(orderNo);
            }
            if (payOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (payWay != payOrder.getPayWay()) {
                rsp.setStrError("订单未使用该支付方式支付");
                return rsp;
            }
            boolean queryOrder = false;
            // 订单状态未知，到第三方查询
            if (PayOrder.PAY_UNKNOWN == payOrder.getPayStatus()) {
                payOrderService.updatePayOrderStatus(payOrder);
                queryOrder = true;
            }
            if (PayOrder.PAY_SUCCESS == payOrder.getPayStatus()) {
                if (queryOrder) {
                    if (1 == payOrder.getFeeType() || 2 == payOrder.getFeeType()) { // 是支付停车费
                        // 将支付消息添加到消息队列中
                        PayOrderMessageList.addPayOrderMessage(payOrder);
                    }
                }
                rsp.setResult(AppBusinessRsp.SUCCESS);
                return rsp;
            } else if (PayOrder.PAY_FAIL == payOrder.getPayStatus()) {
                rsp.setStrError("支付失败！");
                return rsp;
            } else {
                rsp.setStrError("请稍后查询！");
            }
        } catch (Exception e) {
            logger.error("APP付款后查询支付结果异常:{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }


    /**
     * 查询广告费订单
     *
     * @param transactionId 交易订单号
     * @param orderNo       商户订单号
     * @param payWay        支付方式
     * @return AppBusinessRsp
     */
    private AppBusinessRsp queryOrderForAdFee(String transactionId, String orderNo, int payWay) {
        AppBusinessRsp rsp = new AppBusinessRsp();
        rsp.setResult(-1);
        try {
            AdPayOrder adPayOrder = null;
            // 优先根据transactionId查询
            if (!StringUtils.isEmpty(transactionId)) {
                adPayOrder = adPayOrderMapper.getByTransactionId(transactionId);
            } else if (!StringUtils.isEmpty(orderNo)) {
                adPayOrder = adPayOrderMapper.getByOrderNo(orderNo);
            }
            if (adPayOrder == null) {
                rsp.setStrError("订单号错误！");
                return rsp;
            }
            if (payWay != adPayOrder.getPayWay()) {
                rsp.setStrError("订单未使用该支付方式支付");
                return rsp;
            }
            // 根据tranactionId查询，没查到订到，直接到第三方查询
            // 订单状态未知，到第三方查询
            if (adPayOrder.getStatus() != AdPayOrder.STATUS_WAIT_PAY) {
                adPayOrderService.updatePayOrderStatus(adPayOrder);
            }
            if (AdPayOrder.STATUS_WAIT_REVIEW == adPayOrder.getStatus()) {
                rsp.setResult(AppBusinessRsp.SUCCESS);
                return rsp;
            } else if (AdPayOrder.STATUS_CLOSE == adPayOrder.getStatus()) {
                rsp.setStrError("支付失败！");
                return rsp;
            } else {
                rsp.setStrError("请稍后查询！");
            }
        } catch (Exception e) {
            logger.error("APP付款后查询支付结果异常:{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }


    private String getServiceOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&appid="
                + "wx832756d16af60c8c"
                + "&secret=" + "541ae9a46562d2c09b6662a16127e9fc"
                + "&code=" + code;
        String result = HttpsUtil.get(url, null, null);
        logger.info("微信授权获取用户信息：{}", result);
        try {
            WechatTokenRsp wechatTokenRsp = ObjectMapperUtils.getObjectMapper().readValue(result, WechatTokenRsp.class);
            if (wechatTokenRsp != null && wechatTokenRsp.getOpenid() != null) {
                return wechatTokenRsp.getOpenid();
            } else {
                logger.error("【微信公众号，服务商】微信授权获取用户信息失败！");
            }
        } catch (IOException e) {
            logger.error("【服务商】获取openId异常：{}", e);
        }
        return null;
    }

    private void updatePayWayAtUndefiedOrder(Integer payOrderId, Integer tradeType, Integer payWay, Integer isv, Integer apiUserId) {
        PayOrder payOrder1 = new PayOrder();
        payOrder1.setId(payOrderId);
        payOrder1.setTradeType(tradeType);
        payOrder1.setPayWay(payWay);
        payOrder1.setIsv(0);
        payOrder1.setApiUserId(apiUserId);
        payOrder1.setPayStatus(PayOrder.PAY_UNKNOWN);
        payOrderMapper.updatePayWayInfo(payOrder1);
    }
}
